package net.gyapp.markim;

import android.app.ActivityManager;
import android.app.Application;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
import android.support.multidex.MultiDexApplication;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.easyder.wrapper.ManagerConfig;
import com.easyder.wrapper.utils.LogUtils;
import com.lqr.emoji.IImageLoader;
import com.lqr.emoji.LQREmotionKit;

import net.gyapp.markim.core.ImManager;
import net.gyapp.markim.module.basic.Helper;
import net.gyapp.markim.module.mine.vo.MemberVo;

import java.util.Iterator;
import java.util.List;

import static android.content.pm.PackageManager.GET_SERVICES;

/**
 * Auther:  winds
 * Data:    2018/2/27
 * Desc:
 */
public class WrapperApplication extends MultiDexApplication {

    private static Application instance;
    private static MemberVo member;

    @Override
    public void onCreate() {
        super.onCreate();
        if (isRetryInit()) {
            return;
        }
        instance = this;
        //初始wrapper包的manager
        ManagerConfig.getInstance().init(this)
                .setBaseHost(ApiConfig.HOST)
                .initHttpClient()
                .setLogConfig("/MarkIM/Log", true, false);
        ImManager.getInstance(); //消息全局启动并监听
        LQREmotionKit.init(this, new IImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                Glide.with(context).load(path).apply(new RequestOptions().centerCrop().diskCacheStrategy(DiskCacheStrategy.RESOURCE)).into(imageView);
            }
        });
    }

    public static Application getInstance() {
        return instance;
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    public static boolean isLogin() {
        return getMember() != null;
    }

    public static void setMember(MemberVo member) {
        WrapperApplication.member = member;
        Helper.saveMemberInfo(member);
    }

    public static MemberVo getMember() {
        if (member == null) {
            member = Helper.getMemberInfo();
        }
        return member;
    }

    public boolean isRetryInit() {
        int pid = android.os.Process.myPid();
        String processAppName = getAppProcessName(pid);
        LogUtils.info(" processAppName---" + processAppName);
        //默认的app会在以包名为默认的process name下运行，如果查到的process name不是APP的process name就return掉
        String name = getPackageName();
        if (processAppName == null || !processAppName.equalsIgnoreCase(name)) {
            LogUtils.info("enter the service process!");
            // 则此application::onCreate 是被service 调用的，直接返回
            return true;
        }
        return false;
    }

    private String getAppProcessName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return processName;
    }


    public static boolean isInServiceProcess(Context context, Class<? extends Service> serviceClass) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        try {
            packageInfo = packageManager.getPackageInfo(context.getPackageName(), GET_SERVICES);
        } catch (Exception e) {

            return false;
        }
        String mainProcess = packageInfo.applicationInfo.processName;

        ComponentName component = new ComponentName(context, serviceClass);
        ServiceInfo serviceInfo;
        try {
            serviceInfo = packageManager.getServiceInfo(component, 0);
        } catch (PackageManager.NameNotFoundException ignored) {
            // Service is disabled.
            return false;
        }

        if (serviceInfo.processName.equals(mainProcess)) {
            // Technically we are in the service process, but we're not in the service dedicated process.
            return false;
        }

        int myPid = android.os.Process.myPid();
        ActivityManager activityManager =
                (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.RunningAppProcessInfo myProcess = null;
        List<ActivityManager.RunningAppProcessInfo> runningProcesses =
                activityManager.getRunningAppProcesses();
        if (runningProcesses != null) {
            for (ActivityManager.RunningAppProcessInfo process : runningProcesses) {
                if (process.pid == myPid) {
                    myProcess = process;
                    break;
                }
            }
        }
        if (myProcess == null) {
            return false;
        }

        return myProcess.processName.equals(serviceInfo.processName);
    }
}
